<script>
// let baseUrl = 'http://localhost:8080'
import {readExcelToJson, saveJsonToExcel} from '../utils.js'
import axios from "axios";

export default {
  data() {
    return {
      file: null,   // 导出
      sysDictData: {
        dictCode: '',
        dictSort: '',
        dictLabel: '',
        dictValue: '',
        dictType: '',
        cssClass: '',
        listClass: '',
        isDefault: '',
        status: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        remark: '',
      },
      sysDictDataAndDate: {
        current: '',
        size: '',
        dictType: '',
        dictLabel: '',
        status: '',
      },
      thisTypeName: this.$route.params.dictType, // 该页面的类型名
      visible: false, // 弹出确认框
      dateTimeFile: '', // 查询时间范围
      dialogVisible: false, // 开启弹框
      selectionLength: 0, // 多选框被选中个数
      selectionList: [],  // 多选框被选中集合
      sysDictDataS: [], //用户列表
      sysDictDataAll: [],//所有的用户列表
      dateName: '',  // 导出命名
      current: 1,     // 当前页数
      size: 10,        // 每页条数
      pages: 1,       // 页面数
      total: 0,       // 总条数
    }
  },
  methods: {
    /*导出为excel*/
    // 读取文件为json数据
    onUploadChange(file) {
      this.file = file
      readExcelToJson(file).then((res) => {
        this.sysDictTypes = res
      })
    },
    // 导出文件名
    handleDownload(dataName) {
      if (dataName === '') {
        dataName = 'default';
      }
      if (this.selectionList.length === 0) {
        saveJsonToExcel(this.sysDictTypes, dataName + '.xlsx')
      } else {
        axios.post("http://localhost:8080/sysDictType-exportNumber", this.selectionList)
            .then(result => {
              saveJsonToExcel(result.data.data, dataName + '.xlsx')
            })
      }
      this.isNull();
      this.openYes("导出成功");
    },
    // 清空输入框
    isNull() {
      this.dateName = '';
    },
    /*获取所有数据*/
    loadAll: function () {
      axios.get("http://localhost:8080/sysDictType-all")
          .then(result => {
            this.sysDictDataAll = result.data.data;
          })
      console.log("获取所有记录")
    },

    /*删除一条数据*/
    deleteSysDictData(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete("http://localhost:8080/sysDictData/" + id)
            .then(result => {
              this.loadFindPage(this.current);
              this.openYes("成功删除")
            })
            .catch(() => {
              console.log('失败');
              this.loadFindPage(this.current);
            });
      }).catch(() => {
        console.log("取消删除");
      });
    },
    /*删除多条数据*/
    deleteSomeSysDictData() {
      if (this.selectionList.length === 0) {
        this.openWarning("请选择后再删除")
      } else {
        this.$confirm('此操作将永久删除这些数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios({
            headers: {
              'Content-Type': 'application/json'
            },
            method: "post",
            url: "http://localhost:8080/sysDictData-some",
            //指定 json 类型后，传输的数据理所当然应该是 json 格式。
            data: this.selectionList
          })
              .then(() => {
                console.log('成功');
                this.loadFindPage(this.current);
                this.openYes("成功删除")
              })
              .catch(() => {
                console.log('失败');
                this.loadFindPage(this.current);
              });
        }).catch(() => {
          console.log("取消删除");
        });
      }
    },
    /*清除缓存*/
    clearCache(){
      this.$confirm('此操作将永久清除所有记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post('http://localhost:8080/sysDictData-clearCache')
            .then(result => {
              this.openYes("缓存清除成功！")
              this.loadFindPage(this.current);
            })
            .catch(() => {
              console.log('失败');
              this.loadFindPage(this.current);
            });
      }).catch(() => {
        console.log("取消删除");
      });
    },
    /*添加一条数据*/
    addSysDictData() {
      /*加入登录着用户名*/
      // this.sysDictData.createBy = localStorage.getItem("username");
      this.sysDictData.dictType = this.thisTypeName;
      console.log("添加")
      axios.post("http://localhost:8080/sysDictData", this.sysDictData)
          .then(result => {
            this.loadFindPage(this.current);
            this.openYes("已新增一条记录")
          })
      // 结束将对象归零
      this.sysDictData = {
        dictCode: '',
        dictName: '',
        dictType: '',
        status: '',
        remark: '',
        createTime: '',
        createBy: '',
        updateBy: '',
        updateTime: '',
      }
    },
    /*回填数据*/
    backFll(data) {
      /*加入登录着用户名*/
      // this.sysDictData.createBy = localStorage.getItem("username");
      this.sysDictData.dictType = this.thisTypeName;
      this.sysDictData.dictCode = data.dictCode;
      this.sysDictData.dictLabel = data.dictLabel;
      this.sysDictData.dictValue = data.dictValue;
      this.sysDictData.dictSort = data.dictSort;
      this.sysDictData.status = data.status;
      this.sysDictData.remark = data.remark;
    //   css_class,list_class还未完成
    },
    /*更新一条数据*/
    updateSysDictData() {
      axios.put("http://localhost:8080/sysDictData", this.sysDictData)
          .then(result => {
            this.openYes("已更新一条记录")
            this.loadFindPage(this.current);
          })
      // 结束将对象归零
      this.sysDictData = {
        dictCode: '',
        dictName: '',
        dictType: '',
        status: '',
        remark: '',
        createTime: '',
        createBy: '',
        updateBy: '',
        updateTime: '',
      }
    },
    /*更新多条数据*/
    updateSomeSysDictData() {
      console.log("批量修改")
      if (this.selectionList.length === 0) {
        this.openWarning("请选择后再修改")
      } else if (this.selectionList.length !== 1) {
        this.openWarning("你见过批量修改？这里只能选一个，要不你直接用这个👇修改得了")
      } else {
        /*跳转修改*/
        axios.get("http://localhost:8080/sysDictData-one?dictCode=" + this.selectionList)
            .then(result => {
              this.dialogVisible = true;
              this.backFll(result.data.data);
            })
      }
    },
    /*询问是否需要关闭*/
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.openNotice('已关闭')
            done();
          })
          .catch(_ => {
          });
    },
    /*查询数据*/
    loadFindPage(current) {
      this.current = current;
      if (this.sysDictDataAndDate.status !== '') {
        this.sysDictDataAndDate.status = this.sysDictDataAndDate.status === '开启' ? 1 : 0;
      }
      this.sysDictDataAndDate.current = this.current
      this.sysDictDataAndDate.size = this.size
        axios.post("http://localhost:8080/sysDictData-find", this.sysDictDataAndDate)
            .then(result => {
              if(this.sysDictDataAndDate.status !== '') {
                this.sysDictDataAndDate.status = this.sysDictDataAndDate.status === 1?'开启':'关闭';
              }
              console.log(result.data.data.records)
              this.sysDictDataS = result.data.data.records;
              this.current = result.data.data.current;
              this.size = result.data.data.size;
              this.pages = result.data.data.pages;
              this.total = result.data.data.total;
            })

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      //dicId属性值集合
      this.selectionList = selection.map(item => item.dictCode);
      //被选中个数
      this.selectionLength = selection.length;
    },
    /*消息*/
    openNotice(string) {
      this.$notify.info({
        title: '消息',
        message: string,
      });
    },
    /*成功*/
    openYes(string) {
      this.$notify({
        title: '成功',
        message: string,
        type: 'success'
      });
    },
    /*警告*/
    openWarning(string) {
      this.$notify({
        title: '警告',
        message: string,
        type: 'warning'
      });
    },
    /*错误*/
    openError(string) {
      this.$notify.error({
        title: '错误',
        message: string,
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.loadFindPage(this.current)

    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.loadFindPage(val);
    },
  },
  mounted: function () {
    this.loadAll();
    this.sysDictDataAndDate.dictType = this.thisTypeName
    this.loadFindPage(1);
  }
}

</script>

<template>
  <div>
    <!--    模糊查询-->
    <p class="demo-input-suffix" style="text-align: left">
      字典名称：
      <el-select v-model="sysDictDataAndDate.dictType" placeholder="请选择">
        <el-option
            v-for="item in sysDictDataAll"
            :key="item.dictType"
            :label="item.dictName"
            :value="item.dictType">
        </el-option>
      </el-select>
      字典标签：
      <el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="sysDictDataAndDate.dictLabel"
                class="input-wc"></el-input>
      状态：
      <el-radio-group v-model="sysDictDataAndDate.status" style="margin-right: 20px">
        <el-radio-button label="开启"></el-radio-button>
        <el-radio-button label="关闭"></el-radio-button>
      </el-radio-group>
      <el-button type="primary" icon="el-icon-search" @click="loadFindPage(1)" style="margin-left: 20px">搜索
      </el-button>
    </p>
    <!--    范围操作按钮-->
    <div>
      <p style="text-align: left">
        <el-button type="primary" @click="dialogVisible = true"><i class="el-icon-plus" style="margin-right: 10px"/>新增
        </el-button>
        <el-button type="success" @click="updateSomeSysDictData()"><i class="el-icon-edit" style="margin-right: 10px"/>修改
        </el-button>
        <!--    确认气泡-->
          <el-button type="danger" slot="reference" @click="deleteSomeSysDictData()"><i class="el-icon-delete" style="margin-right: 10px"/>删除
          </el-button>
        <el-button type="warning" @click="handleDownload"><i class="el-icon-download" style="margin-right: 10px"/>导出
        </el-button>
        <el-button type="danger" @click="clearCache" ><i class="el-icon-refresh" style="margin-right: 10px"/>清除缓存</el-button>
      </p>
      <!--      表格显示所有数据-->
      <el-table :data="sysDictDataS" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="dictCode" label="字典编码" width="180"></el-table-column>
        <el-table-column prop="dictLabel" label="字典标签" width="180"></el-table-column>
        <el-table-column prop="dictSort" label="字典排序" width="180"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="thisRecord">
            <el-button type="primary" icon="el-icon-edit" circle
                       @click="dialogVisible = true;backFll(thisRecord.row)"></el-button>
            <!--    确认气泡-->
              <el-button type="danger" icon="el-icon-delete" slot="reference" @click="deleteSysDictData(thisRecord.row.dictCode)" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--    新增修改弹框-->
    <el-dialog title="新增字典记录" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <div>
        <table>
          <!--不可编辑-->
          <tr>
            <td><span style="font-size: 18px">字典类型：</span></td>
            <td>
              <el-input type="text" v-model="this.thisTypeName" :disabled="true" show-word-limit class="input-wc-add"/>
            </td>
          </tr>
          <tr>
            <td><span style="font-size: 18px">字典标签：</span></td>
            <td>
              <el-input type="text" placeholder="请输入内容" v-model="sysDictData.dictLabel" maxlength="10"
                        show-word-limit class="input-wc-add"/>
            </td>
          </tr>
          <tr>
            <td><span style="font-size: 18px">字典键值：</span></td>
            <td>
              <el-input type="text" placeholder="请输入内容" v-model="sysDictData.dictValue" maxlength="10"
                        show-word-limit class="input-wc-add"/>
            </td>
          </tr>
          <tr>
            <td><span style="font-size: 18px">字典排序：</span></td>
            <td>
              <el-input-number v-model="sysDictData.dictSort" controls-position="right" :min="1" :max="10"
                               class="input-wc-add" style=""></el-input-number>
            </td>
          </tr>
          <tr>
            <td><span style="font-size: 18px">状态：</span></td>
            <td>
              <div style="margin-top: 20px;float: left">
                <el-radio v-model="sysDictData.status" label="1" border size="medium">正常</el-radio>
                <el-radio v-model="sysDictData.status" label="0" border size="medium">停用</el-radio>
              </div>
            </td>
          </tr>
          <tr>
            <td><span style="font-size: 18px">备注：</span></td>
            <td>
              <el-input type="textarea" placeholder="请输入内容" v-model="sysDictData.remark" maxlength="30"
                        show-word-limit class="input-wc-add"/>
            </td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false,openNotice('已取消添加')">取 消</el-button>
    <el-button type="primary"
               @click="dialogVisible = false;sysDictData.dictCode === ''|| sysDictData.dictCode === null ?addSysDictData():updateSysDictData()">确 定</el-button>
  </span>
    </el-dialog>
    <!--    分页-->
    <div class="block" style="margin-top: 10PX">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page=current :page-sizes="[10,50,100, 300, 500]" :page-size=size
                     layout="total, sizes, prev, pager, next, jumper" :total=total>
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.input-wc {
  width: 200px;
  margin-right: 20px;
}

.input-wc-add {
  width: 400px;
  margin-right: 20px;
  margin: 20px 20px 21px auto;
}
</style>
